<template>
<div id="goods-list">
    <div class="search-add">
        <label for="search" class="label-search">
            <input 
                type="text" 
                id="search" 
                class="inp-search" 
                v-model="searchVal"
                placeholder='模糊查找（例：七匹狼）'
            >
            <my-button
                type='search'
                class="search"
                @click.native='handleClickSearch'
            >搜索</my-button>
        </label>
        <my-button
            type='add'
            link 
            :to="{name: 'addGoods'}"
        >添加商品</my-button>
    </div>
    <div class="div-table-layout">
        <my-table :list='partGoodsList'>
            <template v-slot:th>
                <th 
                    scope='col' 
                    v-for="item in thList" 
                    :key="item"
                    :title='item'
                >{{item}}</th>
            </template>
            <template v-slot:td='{td, index}'>
                <th scope='row'>{{index}}</th>
                <td 
                    style="text-align: left;" 
                    :title='td.goods_name'
                >
                    {{td.goods_name}}
                </td>
                <td>{{td.goods_price}}</td>
                <td>{{td.goods_weight}}</td>
                <td :title='td.add_time | formatTime'>{{td.add_time | formatTime}}</td>
                <td>
                    <div class="btn-group">
                        <my-button 
                            type='edit' 
                            link 
                            :to='{name: "editGoods", params: {
                                goods_id: td.goods_id, 
                                goods_name: td.goods_name, 
                                goods_price: td.goods_price, 
                                goods_weight: td.goods_weight, 
                            }}'
                        >编辑</my-button>
                        <my-button 
                            type='delete'
                            @click.native='handleClickDeleteThisGoods(td.goods_id)'
                        >删除</my-button>
                    </div>
                </td>
            </template>
        </my-table>
    </div>
    <my-paging 
        :total="goods_total"
        :pagetotal="partGoodsListLen"
        :pagenum="newGoodsPageTotal"
        :page.sync="newPage"
        :count.sync="newCount"
    ></my-paging>
</div>
</template>

<script>
import {
    Local, utils
} from '../../common'
import { 
    GOODS_LIST
} from '../../config/localConstant'
import { 
    getGoodsList, 
    searchGoods, 
    deleteGoods
} from '../../config/data'
import { messageTip } from '../JS'
export default {
    name: "goodsList",
    data() {
        return {
            partGoodsList: [], /* 分页后的数据 */
            goods_currPage: 1, /* 商品当前页 */
            goods_count: 2, /* 一页中的数据数量 */
            goods_total: 0, /* 共有多少条数据 */
            goods_pageTotal: 1, /* 总页数 */
            searchVal: '',
            pret: 0
        }
    },
    created() {
        this.getGoodsListData()
    },
    methods: {
        async handleClickDeleteThisGoods(gid) {
            let flag = window.confirm('确定删除？')
            if(!flag) return;
            let result = await deleteGoods({goodsId: gid})
            if(!result.fsBool) return;
            let { msg } = Local.get(GOODS_LIST.KEY)
            msg = msg ? msg : {}
            msg[GOODS_LIST.SELECTED_PAGE_NUMBER] = Math.ceil(result.data.len / msg[GOODS_LIST.SELECTED_PAGE_OF_COUNT]) || 1
            Local.set(GOODS_LIST.KEY, msg)
            messageTip({content: "删除成功"})
            setTimeout(this.getGoodsListData, 60)
        },
        async handleClickSearch() {
            let nowt = Number(Date.now())
            if(nowt - this.pret < 1000) {
                messageTip({content: "太快了，受不了啦！！"})
                return;
            }
            this.pret = nowt
            this.searchVal = this.searchVal.replace(/\s/g, '')
            if(!this.searchVal) return;
            let result = await searchGoods({
                goodsInfo: this.searchVal
            })
            let { msg } = Local.get(GOODS_LIST.KEY)
            msg = msg ? msg : {}
            let pageNumber = msg[GOODS_LIST.SELECTED_PAGE_NUMBER]
            let pageCount = msg[GOODS_LIST.SELECTED_PAGE_OF_COUNT]
            if(result.data.lists?.length > 0) {
                messageTip({content: "搜索成功"})
                this.partGoodsList = result.data.lists
                this.goods_total = result.data.lists.length
                this.goods_pageTotal = Math.ceil(this.goods_total / pageCount) || 1
                this.goods_currPage = 1
                this.goods_count = 10
                
            } else {
                messageTip({content: '暂无查找数据 `' + this.searchVal + '`'})
            }
        },
        async getGoodsListData() {
            let { msg } = Local.get(GOODS_LIST.KEY)
            msg = msg ? msg : {}
            this.goods_currPage = msg[GOODS_LIST.SELECTED_PAGE_NUMBER] || this.goods_currPage
            this.goods_count = msg[GOODS_LIST.SELECTED_PAGE_OF_COUNT] || this.goods_count
            let result = await getGoodsList({
                page: this.goods_currPage,
                count: this.goods_count
            })
            let {
                page, count, total, pageTotal, currPageData
            } = result.data
            this.partGoodsList = currPageData
            this.goods_currPage = page
            this.goods_count = count
            this.goods_total = total
            this.goods_pageTotal = pageTotal
        }
    },
    computed: {
        thList() {
            return ['#', '商品名称', '商品价格（元）', '商品重量', '创建时间', '操作'];
        },
        partGoodsListLen() {
            return this.partGoodsList.length;
        },
        newGoodsPageTotal() {
            return this.goods_pageTotal;
        },
        newPage: {
            get() {
                let { msg } = Local.get(GOODS_LIST.KEY)
                msg = msg ? msg : {}
                this.goods_currPage = msg[GOODS_LIST.SELECTED_PAGE_NUMBER] || 1
                return this.goods_currPage;
            },
            set(val) {
                this.goods_currPage = Number(val)
                let { msg } = Local.get(GOODS_LIST.KEY)
                msg = msg ? msg : {}
                msg[GOODS_LIST.SELECTED_PAGE_NUMBER] = this.goods_currPage
                Local.set(GOODS_LIST.KEY, msg)
                this.getGoodsListData()
            }
        },
        newCount: {
            get() {
                let { msg } = Local.get(GOODS_LIST.KEY)
                msg = msg ? msg : {}
                return msg[GOODS_LIST.SELECTED_PAGE_OF_COUNT] || this.goods_count;
            },
            set(val) {
                this.goods_count = Number(val)
                let { msg } = Local.get(GOODS_LIST.KEY)
                msg = msg ? msg : {}
                msg[GOODS_LIST.SELECTED_PAGE_OF_COUNT] = this.goods_count
                Local.set(GOODS_LIST.KEY, msg)
                this.getGoodsListData()
            }
        },
    },
    filters: {
        formatTime(val) {
            let ct = new Date(Number(val+'000'))
            const obj = {
                y: ct.getFullYear(),
                m: ct.getMonth() + 1,
                d: ct.getDate(),
                h: ct.getHours(),
                mm: ct.getMinutes(),
                s: ct.getSeconds()
            }
            for (const key in obj) {
                obj[key] = utils.addZero(obj[key])
            }
            return `${obj.y}-${obj.m}-${obj.d} ${obj.h}:${obj.mm}:${obj.s}`;
        }
    }
}
</script>

<style scoped>
#goods-list {
    height: 100%;
}
.search-add {
    display: flex;
    align-items: center;
    width: 100%;
    height: 50px;
    line-height: 50px;
    white-space: nowrap;
    z-index: 5;
}
.search-add .label-search {
    display: flex;
    height: 30px;
    line-height: 30px;
    margin-right: 12px;
    border: 1px solid #cecece;
    border-radius: 5px;
}
.inp-search {
    height: 26px;
    line-height: 26px;
    padding: 2px 6px;
    border: none;
    outline: none;
    border-radius: 5px 0 0 5px;
    font-size: 18px;
}
.search {
    margin-top: -1px;
    margin-right: -1px;
    border: none;
    border-radius: 0 5px 5px 0;
}
.div-table-layout {
    height: calc(100% - 100px);
}
th:nth-of-type(1) {
    width: 64px;
}
th:nth-of-type(3),
th:nth-of-type(4), 
td:nth-of-type(2),
td:nth-of-type(3) {
    width: 100px;
}
.table-thead th:last-of-type,
td:last-of-type {
    width: 140px;
}

.btn-group {
    display: flex;
    justify-content: center;
    align-items: center;;
}
.btn-group :nth-child(1), 
.btn-group :nth-child(2) {
    margin: 0 6px;
}

</style>